<script setup>
import { ref, computed, onUpdated } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import Bus from '../utils/bus'

const cartItems = ref([])

// 监听添加商品事件
Bus.on('add-to-cart', (product) => {
  const existing = cartItems.value.find(item => item.id === product.id)
  if (existing) {
    existing.number++
  } else {
    cartItems.value.push({ ...product, number: 1 })
  }
})

const totalPrice = computed(() => 
  cartItems.value.reduce((total, item) => total + item.price * item.number, 0)
)

const handleChange = (item) => {
  if (item.number <= 0) {
    removeFromCart(item)
  }
}

const removeFromCart = (item) => {
  const index = cartItems.value.indexOf(item)
  if (index > -1) {
    cartItems.value.splice(index, 1)
  }
}

const checkout = () => {
  ElNotification({
    title: '结算成功',
    message: `总金额：${totalPrice.value} 元`,
    type: 'success'
  })
  cartItems.value = []
}

// 库存检查
onUpdated(() => {
  cartItems.value.forEach(item => {
    if (item.number > item.stock) {
      item.number = item.stock
      ElMessage.warning(`${item.name} 库存不足，已调整为最大数量 ${item.stock}`)
    }
  })
})
</script>

<template>
  <el-card class="cart-card">
    <h2>购物车</h2>
    <div v-if="cartItems.length > 0">
      <div v-for="(item, i) in cartItems" :key="item.id">
        <el-row align="middle">
          <el-col :span="14">
            <div class="item-info">
              <span class="item-name">{{ item.name }}</span>
              <span class="item-price">¥{{ item.price }} × {{ item.number }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-input-number 
              v-model="item.number" 
              :min="0" 
              :max="item.stock"
              @change="handleChange(item)"
              size="small"
            />
          </el-col>
          <el-col :span="2">
            <el-button 
              type="danger" 
              icon="Delete" 
              @click="removeFromCart(item)" 
              circle 
              size="small"
            />
          </el-col>
        </el-row>
        <el-divider v-if="i < cartItems.length - 1" />
      </div>
    </div>
    <el-empty v-else description="购物车空空如也" />
    
    <div class="checkout-section">
      <el-text size="large" tag="b">总计：¥{{ totalPrice }}</el-text>
      <el-button 
        type="primary" 
        @click="checkout" 
        :disabled="cartItems.length === 0"
        class="checkout-btn"
      >
        立即结算
      </el-button>
    </div>
  </el-card>
</template>

<style scoped>
.cart-card {
  position: sticky;
  top: 20px;
}
.item-info {
  display: flex;
  flex-direction: column;
}
.item-name {
  font-size: 0.9rem;
  margin-bottom: 4px;
}
.item-price {
  font-size: 0.8rem;
  color: #666;
}
.checkout-section {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.checkout-btn {
  margin-left: auto;
}
</style>